import React, { useState } from 'react';
import '../../../../css/maintenan/addDevicel.less'; // 引入CSS样式文件
import { PlusOutlined } from '@ant-design/icons';
import { Image, message, Upload } from 'antd';
import type { GetProp, UploadFile, UploadProps } from 'antd';
import { addDaily } from '../../../../../../api/csy/api'
import { useNavigate } from 'react-router-dom';
type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

const getBase64 = (file: FileType): Promise<string> =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result as string);
        reader.onerror = (error) => reject(error);
    });




// 模拟的选项数据（可以根据实际情况调整）
const repairReasons = ['设备故障', '定期检查', '其他'];
const devices = ['设备A', '设备B', '设备C'];

const RepairForm: React.FC = () => {
    const [projectName, setProjectName] = useState('');
    const [repairReason, setRepairReason] = useState(repairReasons[0]); // 默认选择第一个维修原因
    const [selectedDevice, setSelectedDevice] = useState(devices[0]); // 默认选择第一个设备
    const [plannedCompletionTime, setPlannedCompletionTime] = useState('');
    const [assignedPersonnel, setAssignedPersonnel] = useState('');
    const [taskIssuer, setTaskIssuer] = useState('');
    //图片上传
    const navigate = useNavigate();


    const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
        console.log(123123);
        event.preventDefault();
        addDaily({
            projectName,
            repairReason,
            selectedDevice,
            // 注意：这里省略了repairPhoto的上传逻辑，需要根据实际情况实现
            plannedCompletionTime,
            assignedPersonnel,
            taskIssuer,
            fileList,
        }).then(res => {
            if (res.data.code == 200) {
                message.success('添加成功')
                setFileList([])
                setProjectName('')
                setRepairReason('')
                setSelectedDevice('')
                setPlannedCompletionTime('')
                setAssignedPersonnel('')
                setTaskIssuer('')
                navigate('/service/Operational/maintenance/DailyMaintenance/indexDaily')

            }
        })

        // 在这里处理表单提交逻辑，例如发送到服务器
        console.log('维修表单数据:', {
            projectName,
            repairReason,
            selectedDevice,
            // 注意：这里省略了repairPhoto的上传逻辑，需要根据实际情况实现
            plannedCompletionTime,
            assignedPersonnel,
            taskIssuer,
            fileList,
        });
    };
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [fileList, setFileList] = useState<UploadFile[]>([]);

    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as FileType);
        }

        setPreviewImage(file.url || (file.preview as string));
        setPreviewOpen(true);
    };

    const handleChange: UploadProps['onChange'] = ({ fileList }) =>
        setFileList(fileList);
    const uploadButton = (
        <button style={{ border: 0, background: 'none' }} type="button">
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
        </button>
    );
    const dain = () => {
        setFileList([])
        setProjectName('')
        setRepairReason('')
        setSelectedDevice('')
        setPlannedCompletionTime('')
        setAssignedPersonnel('')
        setTaskIssuer('')
        navigate('/service/Operational/maintenance/DailyMaintenance/indexDaily')
    }


    return (
        <form className="repair-form" onSubmit={handleSubmit}>
            <div className="form-group">
                <label htmlFor="projectName">工程名称：</label>
                <input
                    type="text"
                    id="projectName"
                    value={projectName}
                    onChange={(e) => setProjectName(e.target.value)}
                    placeholder="请输入工程名称"
                    required
                />
            </div>
            <div className="form-group">
                <label htmlFor="repairReason">维修原因：</label>
                <select
                    id="repairReason"
                    value={repairReason}
                    onChange={(e) => setRepairReason(e.target.value)}
                >
                    {repairReasons.map((reason, index) => (
                        <option key={index} value={reason}>
                            {reason}
                        </option>
                    ))}
                </select>
            </div>
            <div className="form-group">
                <label htmlFor="selectedDevice">关联设备：</label>
                <select
                    id="selectedDevice"
                    value={selectedDevice}
                    onChange={(e) => setSelectedDevice(e.target.value)}
                >
                    {devices.map((device, index) => (
                        <option key={index} value={device}>
                            {device}
                        </option>
                    ))}
                </select>
            </div>
            <div className="form-group">
                <label htmlFor="repairPhoto">维修前照片：</label>
                <Upload
                    action="http://localhost:3000/csy/upload"
                    headers={{
                        Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
                    }}
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={handlePreview}
                    onChange={handleChange}
                >
                    {fileList.length >= 8 ? null : uploadButton}
                </Upload>
                {previewImage && (
                    <Image
                        wrapperStyle={{ display: 'none' }}
                        preview={{
                            visible: previewOpen,
                            onVisibleChange: (visible) => setPreviewOpen(visible),
                            afterOpenChange: (visible) => !visible && setPreviewImage(''),
                        }}
                        src={previewImage}
                    />
                )}
            </div>
            <div className="form-group">
                <label htmlFor="plannedCompletionTime">计划完成时间：</label>
                <input
                    type="datetime-local"
                    id="plannedCompletionTime"
                    value={plannedCompletionTime}
                    onChange={(e) => setPlannedCompletionTime(e.target.value)}
                    required
                />
            </div>
            <div className="form-group">
                <label htmlFor="assignedPersonnel">指派处理人员：</label>
                <input
                    type="text"
                    id="assignedPersonnel"
                    value={assignedPersonnel}
                    onChange={(e) => setAssignedPersonnel(e.target.value)}
                    placeholder="请输入指派处理人员姓名"
                    required
                />
            </div>
            <div className="form-group">
                <label htmlFor="taskIssuer">任务下达人：</label>
                <input
                    type="text"
                    id="taskIssuer"
                    value={taskIssuer}
                    onChange={(e) => setTaskIssuer(e.target.value)}
                    placeholder="请输入任务下达人姓名"
                    required
                />
            </div>
            <div className="form-actions">
                <button type="submit" className="btn btn-primary">
                    发起维修
                </button>
                <button type="button" className="btn btn-secondary" onClick={() => dain()}>
                    取消
                </button>
            </div>
        </form>
    );
};



export default RepairForm;